package com.hnao.serialport

import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import com.alibaba.fastjson.JSONObject
import com.hnao.serialport.utils.sqym.SerialModule
import com.taobao.weex.bridge.JSCallback

/**
 * @Author caow
 * 2025/2/19
 */
object SerialPortApplicationManager {

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (msg.what == 1) {
                val result = msg.obj as String
                Log.i("caow", "handleMessage: $result")
                SerialPortCallbackListener.listener?.invoke(result)
            }
        }
    }

    private val serialModule = SerialModule()

    private val serialInitCallback: JSCallback = object : JSCallback {
        override fun invoke(data: Any?) {
            Log.i("caow", "invoke: $data")
            if (data != null) {
                val json = JSONObject.parseObject(data.toString())
                val status = json.getBoolean("status")
                if (status) {
                    Log.i("caow", "初始化刷卡监听")
                    initListener()
                }
            }
            //            data?.let {
//                val json = JSONObject.parseObject(it.toString())
//                val status = json.getBoolean("status")
//                if (status) {
//                    Log.i("caow", "初始化刷卡监听")
//                    initListener()
//                }
//            }
        }

        override fun invokeAndKeepAlive(data: Any) {
            Log.i("caow", "invokeAndKeepAlive: $data")
        }
    }

    fun init() {
        val json = JSONObject()
        json["path"] = "/dev/ttyS3"
        json["baudRate"] = 9600
        json["dataStartBit"] = 0
        json["dataLength"] = 10
        serialModule.open(json, serialInitCallback)
    }

    private fun initListener() {
        serialModule.registHandler(object : JSCallback {
            override fun invoke(data: Any) {
                Log.i("caow", "invoke: $data")
                if (data != null) {
                    Log.i("caow", "invoke: $data")
                    val json = JSONObject.parseObject(data.toString())
                    val card = json.getString("card")

                    val message = Message.obtain()
                    message.what = 1
                    message.obj = card
                    handler.sendMessage(message)

                }
            }

            override fun invokeAndKeepAlive(data: Any?) {
                Log.i("caow", "invokeAndKeepAlive2: $data")
                if (data != null) {
                    Log.i("caow", "invoke: $data")
                    val json = JSONObject.parseObject(data.toString())
                    val card = json.getString("card")
                    val str: String = convertHex(card)
                    Log.i("caow", "str === $str")

                    val message = Message.obtain()
                    message.what = 1
                    message.obj = str
                    handler.sendMessage(message)
                }
            }
        })
    }

    private fun convertHex(strHex: String): String {
        val sb = StringBuilder()
        var i = 0
        while (i < strHex.length) {
            val tmp = strHex.substring(i, i + 2)
            val charValue = tmp.toInt(16).toChar()
            sb.append(charValue)
            i += 2
        }
        return sb.toString().replace("\r\n", "")
    }

}